<?php


namespace App\Models\CacheModel;


use app\aliyun\controller\AliyunFilterWord;
use App\Models\CacheModel\lucky\AppUserAdornInfo;
use App\Models\CacheModel\zl1_relation\Zl1AstrCommunityArticle;
use App\Models\CacheModel\zl2\Zl2AstrFortuneArticle;
use App\Models\CacheModel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Push;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use App\Models\Api\MessageCenter;
use App\Models\Api\User;
use Exception;
use think\Cache;
use think\Log;
use AstroTool\Cache\CacheManage;

class ArticleCommentReply extends BaseCache
{
    protected $table = 'wechatadmin.system_comment_reply';
    public $cacheModel = 'content.reply';
    // 问答提问者 是否匿名
    public $isAnonymity = false;
    // 问答提问者 匿名头像和昵称
    public $anonymityNickname = '匿名用户';
    public $anonymityAvatar = '/test/question_answer/anonymity1.png';

    /**
     * 删除回复
     * @param $uid
     * @param $id
     * @param $type
     * @return bool
     */
    public function delReply($uid, $id)
    {
        try
        {
            //获取回复详情
            $reply = $this->getInfoById($id, ['aid', 'comment_id', 'type', 'pid', 'uid1']);
            //删除回复
            if ($reply)
            {
                if ($reply['uid1'] != $uid)
                {
                    throw new ApiException('数据不存在');
                }
                $this->where(['id' => $id, 'uid' => $uid])->update(['status' => -1]);
                // 更新评论回复列表
                $this->listDataDel($reply['comment_id'], [$id]);
                //删除回复详情缓存
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
                //更新评论回复数
                $articleCommentModel = new ArticleComment();
                $commentInfo = current($articleCommentModel->batchGetInfo([$reply['comment_id']], ['reply', 'uid']));
                // 评论回复数新增 缓存更新(缓存自动更新，更新之后更新)
                $commentInfo['reply']--;
                $updateReply = ['reply' => $commentInfo['reply']];
                $articleCommentModel->where('id', $reply['comment_id'])->update($updateReply);
                CacheManage::getInstance()->setCacheConfig($articleCommentModel->cacheModel, $reply['comment_id'])->setCache($updateReply);
                $cacheKey = $reply['type'] == 1 ? 'comment' : 'comment_num';
                // 新增文章|动态|话题 评论数 互动数（更新文章评论数）
                $articleCommentModel->commentOrgoodAdd($reply['type'], $reply['aid'], $cacheKey, -1);
                //若当前是回复回复
                if ($reply['pid'])
                {
                    $replyUid = $this->getInfoById($reply['pid'], ['id', 'uid']);
                } //若当前是回复评论
                else
                {
                    $replyUid = $commentInfo;
                }
                //更新用户回复我的list缓存
                CacheManage::getInstance()->setCacheConfig('content.reply_me', $replyUid['uid'] . '-0')->delJudge($id, 'list');
                CacheManage::getInstance()->setCacheConfig('content.reply_me', $replyUid['uid'] . '-' . $reply['type'])->delJudge($id, 'list');
            }
        }
        catch (Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 评论->回复
     * @param array $userInfo
     * @param array $data
     * @param bool $complainSwitch 内容申诉开关
     * @return array
     * @throws ApiException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws Exception
     */
    public function addCommentReply(array $userInfo, array $data, bool $complainSwitch = true)
    {
        if (Util::commentCheck($userInfo['id'], $data))
        {   // 重复评论验证
            return ['status' => false, 'msg' => '重复评论过快'];
        }
        $res = AliyunFilterWord::checkText($data['content'], 'article_comment');
        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            $data['check_status'] = 1;
            $data['illegal_type'] = $res['label_type'];
            $data['illegal_level'] = $res['level'];
            $data['data_id'] = $res['data_id'];
            $data['status'] = -1;
        }
        if (!$complainSwitch && $res)
        {
            return [
                'status' => false,
                'msg' => '当前内容中有敏感词',
            ];
        }

        $data['create_time'] = request()->time();

        $articleCommentModel = new ArticleComment();
        // 获取评论信息
        $commentInfo = current($articleCommentModel->batchGetInfo([$data['comment_id']], ['id', 'type', 'aid', 'reply', 'uid']));
        if (!$commentInfo)
        {
            return ['status' => false, 'msg' => '评论不能存在'];
        }
        if (!$commentInfo['uid'])
        {
            return ['status' => false, 'msg' => '服务异常，请稍后重试～'];
        }
        $data['aid'] = $commentInfo['aid'];
        $data['type'] = $commentInfo['type'];
        $commentReplyId = 0;
        $nickname = '';
        $user_id = 0;
        $replyUserInfo = [];
        try
        {
            //获取对应的内容信息
            switch ($commentInfo['type'])
            {
                case 1:
                    $article = current((new Article())->batchGetInfo([$commentInfo['aid']], ['id', 'title']));
                    break;
                case 2:
                    $article = (new ZlGoddessState())->getInfoById($commentInfo['aid'], ['title']);
                    break;
                case 3:
                    $article = current((new GoddessArea())->batchGetThemeInfo([$commentInfo['aid']], ['id', 'title', 'reply_avatars']));
                    break;
                case 4:
                    $article = (new Zlcr2UserQuestion())->getInfoById($data['aid'], ['question']);
                    $article['title'] = $article['question'];
                    break;
                case 5:
                    $article = (new Zl1AstrCommunityArticle())->getInfoById($data['aid'], ['id', 'title']);
                    break;
                case 6:
                    $article = (new Zl2AstrFortuneArticle())->getInfoById($data['aid'], ['id', 'title']);
                    break;
                default:
                    $article = [];
            }
            if ($article)
            {
                // 评论回复数新增 缓存更新(缓存自动更新，更新之后更新)
                $commentInfo['reply']++;
                $updateReply = ['reply' => $commentInfo['reply']];
                $articleCommentModel->where('id', $data['comment_id'])->update($updateReply);
                // 新增
                $commentReplyId = $this->insertGetId($data);
                // 获取被回复的用户信息
                if ($data['pid'])
                {
                    // 获取评论回复信息
                    $commentReplyInfo = current($this->batchGetInfoByIds($data['pid'], ['uid1']));
                    $replyUserInfo = current((new User())->batchGetUserInfo([$commentReplyInfo['uid1']], ['nickname', 'id']));
                    $nickname = $replyUserInfo['nickname'];
                    $user_id = $commentReplyInfo['uid1'];
                } else
                {
                    $replyUserInfo = current((new User())->batchGetUserInfo([$commentInfo['uid']], ['nickname', 'id']));
                    $nickname = $replyUserInfo['nickname'];
                    $user_id = $commentInfo['uid'];
                }
                // 若当前回复无违规则进行缓存处理
                if (!$res)
                {
                    CacheManage::getInstance()->setCacheConfig('content.comment', $data['comment_id'])->setCache($updateReply);
                    // 添加评论回复ID到 -> 评论回复List 中
                    $this->listDataAdd($data['comment_id'], [$commentReplyId => $commentReplyId]);
                    if (in_array((int)$commentInfo['type'], [1, 2, 3], true))
                    {
                        $cacheKey = $commentInfo['type'] == 1 ? 'comment' : 'comment_num';
                        // 【文章|动态|话题】回复数(互动数)新增
                        $articleCommentModel->commentOrgoodAdd($commentInfo['type'], $commentInfo['aid'], $cacheKey, 1);
                    }
                    if ($commentInfo['type'] == 3 && $userInfo['avatar'])
                    {   // 互动头像添加
                        (new GoddessArea())->interactionAvatars($commentInfo['aid'], $userInfo['avatar'], $article);
                    }
                    //回复我的缓存list添加
                    CacheManage::getInstance()->setCacheConfig('content.reply_me', $user_id . '-0')->listAdd([$commentReplyId => $commentReplyId]);
                    CacheManage::getInstance()->setCacheConfig('content.reply_me', $user_id . '-' . $commentInfo['type'])->listAdd([$commentReplyId => $commentReplyId]);
                    // 删除已读回复缓存
                    Cache::rm('read_reply_' . $user_id);
                    //删除旧版评论回复缓存
                    Cache::rm('comment_reply_id_' . $commentInfo['id']); //根据评论id
                    //删除旧版我的回复缓存
                    Cache::rm('user:reply:' . $user_id); //根据用户id
                }
            }
        }
        catch (Exception $e)
        {
            Log::write('ArticleCommentReply->addCommentReply()回复评论失败：' . $e->getMessage(), 'error');
            return [
                'status' => false,
                'msg' => '服务异常，请稍后再试',
            ];
        }

        // 若内容违规给自己发消息
        if ($res)
        {
            if ($commentReplyId && in_array($commentInfo['type'], [1, 2, 3], false))
            {
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $userInfo['id'],
                    'type' => 1,// 系统消息
                    'article_comment_id' => 0,
                    'article_comment_reply_id' => $commentReplyId,
                    'reid' => 0,
                    'cid' => 0,
                    'title' => '评论内容违禁处理',
                    'content' => '亲爱的用户，您在《' . $article['title'] . '》中的评论[REPLACE]由于涉嫌违禁词汇言论（' . $res['label'] . '）已做隐藏删除处理，若您有异议点击内容申诉官方人工二次审核',
                    'link' => '',
                    'target' => '',
                    'create_time' => request()->time(),
                ];
                // 添加消息
                (new MessageCenter())->pushMessage($userInfo['id'], $messageData);
                throw new ApiException('小准准检测到您的评论涉嫌违规' . PHP_EOL . '已做处理，点击查看详情', 200, 201);
            }
            throw new ApiException('您的回复有敏感词！', 200, 0);
        }
        // 给被回复的用户发推送  若当前回复的用户不为自己，且未违规，则发送推送
        if ($user_id && (int)$userInfo['id'] !== (int)$user_id)
        {
            $messageLink = Util::CheckAppVersion('2.8.0') === '小' ? 'reply_me?need_auth=2' : 'message_center?type=4&need_auth=2';
            // 发送推送
            (new Push())->pushUserMsg($user_id, '您有一条新的回复，请查收', ['action' => 'extend', 'target' => 'local', 'link' => $messageLink], '准了');
        }
        return [
            'status' => true,
            'id' => $commentReplyId,
            'nickname2' => $nickname,
        ];
    }

    /**
     * 获取用户我的回复分页数据
     * @param $uid
     * @return array
     * @throws ApiException
     * @throws \think\Exception
     * @throws Exception
     */
    public function getUserReplyMePage($uid)
    {
        $page = input('page/d', 1);
        $ids = $this->getUserReplyMeFromCache($uid);

        // 获取回复阅读情况
        $read_ids = $this->getUserReadReply($uid);
        //获取用户未读数
        $unread_ids = array_diff($ids, $read_ids);
        (new AppUserReply())->replyRead($uid, $unread_ids);
        $num = count($ids);
        $data_list = getPaginatorData($num, $page);
        //获取分页后的数据
        $ids = array_slice($ids, $data_list['start'], 10);
        $data = $this->batchGetInfoByIds($ids, ['id', 'create_time', 'content', 'duration', 'pid', 'comment_id', 'good_num', 'uid1', 'uid2', 'uid', 'is_goddess', 'content_type', 'type', 'aid']);
        $data_list['data'] = $this->replyMeDataFormat($uid, $ids, $data, 2);
        unset($data_list['start']);
        unset($data_list['end']);
        return $data_list;
    }

    /**
     * 缓存获取用户回复我的所有ids
     * @param $uid
     * @param int $type 0=>全部 1=>星文，2=>女神动态，3=>女神专区 4=>问答, 5=>星座讨论
     * @return array|mixed
     * @throws Exception
     */
    public function getUserReplyMeFromCache($uid, $type = 0)
    {
        $ids = CacheManage::getInstance()->setSort('desc')->setCacheConfig('content.reply_me', $uid . '-' . $type)->ZsGetIocData('list', function () use ($uid, $type)
        {
            try
            {
                $where = [];
                // 处理IOS端低版本，消息中心崩溃的问题
                if (Util::CheckAppVersion('2.9.0') === '小')
                {
                    if (!$type || $type === 5)
                    {
                        $where['cr.type'] = ['<', 5];
                    }
                } elseif ($type)
                {
                    $where['cr.type'] = $type;
                }
                $uid = (int)$uid;
                $ids = $this
                    ->alias('cr')
                    ->field('cr.id')
                    ->join('wechatadmin.system_article_comment ac', 'cr.comment_id=ac.id', 'LEFT')
                    ->join('wechatadmin.system_comment_reply cr2', 'cr.pid=cr2.id', 'LEFT')
                    ->where($where)
                    ->where("cr.status=0 AND ((cr.pid=0 AND ac.uid='{$uid}' AND ac.status=0) OR (cr.pid>0 AND cr2.uid='{$uid}' AND cr2.status=0))")
                    ->order('cr.id', 'DESC')
                    ->column('cr.id', 'cr.id');
                $ids = keyValue($ids);
            }
            catch (Exception $e)
            {
                $ids = [];
            }
            return $ids;
        });
        return $ids;
    }

    /**
     * 获取用户已读的回复id
     * @param $uid
     * @return array|mixed
     * @throws Exception
     */
    public function getUserReadReply($uid)
    {
        return CacheManage::getInstance()->setCacheConfig('user.read_reply', $uid)->ZsGetIocData('list', function () use ($uid)
        {
            try
            {
                $data = $this->table('wechat_backup_07_18_14_43_00.app_user_reply')
                    ->where('uid', $uid)
                    ->column('reply_id', 'reply_id');
                $data = keyValue($data);
            }
            catch (Exception $e)
            {
                $data = [];
            }
            return $data;
        });
    }

    /**
     * 回复我的数据重组
     * @param $uid
     * @param array $ids 回复的id
     * @param array $commentReplyDatas 回复的数据
     * @param int $timeType 时间格式类型 1=>时间戳格式 2=>字符串格式
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws \think\Exception
     * @throws Exception
     */
    protected function replyMeDataFormat($uid, array $ids, array $commentReplyDatas, int $timeType = 1)
    {
        $userIds = [];
        $articleModel = new Article();
        $goddessStateModel = new ZlGoddessState();
        $goddessAreaModel = new GoddessArea();
        $articleCommentModel = new ArticleComment();
        $articleCommentReplyModel = new ArticleCommentReply();
        $goddessInfoModel = new GoddessBaseInfo();
        foreach ($commentReplyDatas as $commentReplyDataItem)
        {
            $userIds[] = $commentReplyDataItem['uid1'];
            $userIds[] = $commentReplyDataItem['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        // 批量获取用户信息
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['avatar', 'nickname']);
        $resData = [];
        //获取内部官方用户
        $configModel = new ConfigManage();
        foreach ($ids as $id)
        {
            if (!$commentReplyDatas[$id]['pid'])
            {
                //获取评论的内容
                $comment = $articleCommentModel->batchGetInfo([$commentReplyDatas[$id]['comment_id']], ['content']);
                $content = $comment ? current($comment)['content'] : '';
            } else
            {
                //获取回复的内容
                $reply = $articleCommentReplyModel->getInfoById($commentReplyDatas[$id]['pid'], ['content']);
                $content = $reply ? $reply['content'] : '';
            }
            //获取文章信息
            switch ($commentReplyDatas[$id]['type'])
            {
                case 1://星文
                    $article = current($articleModel->batchGetInfo([$commentReplyDatas[$id]['aid']], ['id', 'title']));
                    break;
                case 2://动态
                    $article = $goddessStateModel->getInfoById($commentReplyDatas[$id]['aid'], ['id', 'type', 'title']);
                    break;
                case 3://话题
                    $article = current($goddessAreaModel->batchGetThemeInfo([$commentReplyDatas[$id]['aid']], ['id', 'title']));
                    break;
                default:
                    $article = [];
                    break;
            }
            $goddessInfo = [];
            if ($commentReplyDatas[$id]['is_goddess'])
            {
                $goddessInfo = $goddessInfoModel->getInfo(['nickname', 'avatar']);
                if ($goddessInfo)
                {
                    if ($commentReplyDatas[$id]['content_type'] == 2)//回复类型为音频
                    {
                        $goddessInfo['content'] = '一条语音回复';
                    }
                }
            }
            $resData[] = [
                'id' => (int)($article['id'] ?? 0),
                'type' => (int)$commentReplyDatas[$id]['type'],
                'user_type' => $configModel->innerUser((int)($commentReplyDatas[$id]['uid1'] ?? 0)), //获取内部官方用户
                'comment_id' => (int)$commentReplyDatas[$id]['comment_id'],
                'title' => $article['title'] ?? '',
                'nickname1' => $goddessInfo['nickname'] ?? ($userInfoList[$commentReplyDatas[$id]['uid1']]['nickname'] ?? '匿名用户'),
                'avatar' => $goddessInfo['avatar'] ?? ($userInfoList[$commentReplyDatas[$id]['uid1']]['avatar'] ?? '匿名用户'),
                'content1' => $goddessInfo['content'] ?? htmlspecialchars_decode($commentReplyDatas[$id]['content'] ?? ''),
                'nickname2' => $goddessInfo['nickname'] ?? ($userInfoList[$commentReplyDatas[$id]['uid2']]['nickname'] ?? '匿名用户'),
                'content2' => $content,
                'content_type' => (int)($article['type'] ?? 1),//动态文章类型 1=》图文（可分享），2=》竖屏视频，3=》横屏视屏，4》音频，5=》公告
                'time' => $timeType === 1 ? (int)$commentReplyDatas[$id]['create_time'] : Util::timeToStr($commentReplyDatas[$id]['create_time']),
            ];
        }
        return $resData;
    }

    /**
     * 获取分页数据
     * @param $uid
     * @param int $commentId
     * @param int $isOld 是否是旧版本 1=>旧版本2.0.0之前 2=>新版本
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws Exception
     */
    public function getPageCommentReplyList($uid, int $commentId, int $isOld = 2, int $page = 1, int $limit = 10)
    {
        // 获取女神回复List
        $goddessReplyIds = $this->getGoddessReplyIds($commentId);

        $thisPageData = $this->getCommentReplyPageIds($goddessReplyIds, $commentId, $page, $limit);

        if ($thisPageData['data'])
        {
            // 通过ids 批量获取话题详情
            $commentReplyDatas = $this->batchGetInfoByIds($thisPageData['data'], ['create_time', 'content', 'good_num', 'uid1', 'uid2', 'pid', 'aid', 'is_goddess', 'content_type', 'duration']);
            // 重组详情数据
            $thisPageData['data'] = $this->commentReplyDataReset($uid, $thisPageData['data'], $commentReplyDatas, $isOld);
        }

        return $thisPageData;
    }

    /**
     * 获取分页数据 问答
     * @param int $uid
     * @param int $commentUid 讨论发布者用户uid
     * @param int $questionUid 问题发布者用户uid
     * @param int $commentId
     * @param int $page
     * @param int $limit
     * @return array
     * @throws ApiException
     */
    public function getQuestionAnswerPageCommentReplyList(int $uid, int $commentUid, int $questionUid, int $commentId, int $page = 1, int $limit = 10)
    {
        $thisPageData = $this->getCommentReplyPageIds([], $commentId, $page, $limit);
        if ($thisPageData['data'])
        {
            // 通过ids 批量获取话题详情
            $commentReplyDatas = $this->batchGetInfoByIds($thisPageData['data'], ['create_time', 'content', 'good_num', 'uid1', 'uid2', 'pid', 'aid', 'content_type', 'duration']);
            // 重组详情数据
            $thisPageData['data'] = $this->questionAnswerCommentReplyDataReset($uid, $commentUid, $questionUid, $thisPageData['data'], $commentReplyDatas);
        }

        return $thisPageData;
    }

    /**
     * 获取当前评论的女神回复ID
     * @param int $commentId
     * @return array
     * @throws Exception
     */
    public function getGoddessReplyIds(int $commentId): array
    {
        $data = CacheManage::getInstance()->setCacheConfig('goddess_area.goddess_reply_comment', $commentId)
            ->setSort('desc')->ZsGetIocData('list', function () use ($commentId)
            {
                try
                {
                    $ids = $this->where(['comment_id' => $commentId, 'is_goddess' => 1, 'status' => 0])
                        ->order('id desc')->column('id');
                    $resIds = [];

                    foreach ($ids as $id)
                    {
                        $resIds[$id] = $id + 100000000;
                    }
                    return $resIds;
                }
                catch (Exception $e)
                {
                    return [];
                }
            }, true);

        return $data;
    }

    /**
     * 获取评论详情分页数据及评论回复ids
     * @param array $goddessReplyIds
     * @param int $commentId
     * @param int $page
     * @param int $limit
     * @return array
     * @throws Exception
     */
    public function getCommentReplyPageIds(array $goddessReplyIds, int $commentId, int $page, int $limit)
    {
        $idDatas = $this->getCommentReplyAllIds($commentId, 'desc', true);

        $resIdDatas = $goddessReplyIds + $idDatas; // 数组合并保留键名， array_merge()数字键名会重新索引
        arsort($resIdDatas); // 根据值进行倒序排序  [id=>排序值]
        // 获取所有的ids
        $ids = array_keys($resIdDatas);

        $replyIds = [];
        $total = count($ids); // 总评论数
        $lastPage = $page < 1 ? 1 : (int)ceil($total / $limit); // 总页数

        if ($page < 1)
        { // 获取所有ID
            $replyIds = $ids;
        } elseif ($page > 0 && $page <= $lastPage)
        { // 第分页IDS
            $star = ($page - 1) * $limit;
            $replyIds = array_slice($ids, $star, $limit);
        }

        return [
            'total' => $total,// 记录总数
            'per_page' => $page < 1 ? -1 : $limit,// 每页多少条
            'current_page' => $page,// 当前页数
            'last_page' => $lastPage,// 总页数
            'data' => $replyIds,
        ];
    }

    /**
     * 获取评论所有的非女神回复ID
     * @param int $commentId
     * @param string $sort
     * @param null|bool $withscores 是否获取排序分数
     * @return array|mixed
     * @throws Exception
     */
    public function getCommentReplyAllIds(int $commentId, string $sort = 'desc', $withscores = null)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $commentId)
            ->setSort($sort)->ZsGetIocData('list', function () use ($commentId)
            {
                try
                {
                    $data = $this->where(['comment_id' => $commentId, 'is_goddess' => 0, 'status' => 0])
                        ->order('id desc')->column('id');
                    $ids = [];
                    foreach ($data as $id)
                    {
                        $ids[$id] = $id;
                    }
                }
                catch (Exception $e)
                {
                    $ids = [];
                }
                return $ids;
            }, $withscores);
    }

    /**
     * 分页数据重组
     * @param $uid
     * @param array $ids
     * @param array $commentReplyDatas
     * @param int $isOld 是否是旧版本 1=>旧版本2.0.0之前 2=>新版本
     * @return array
     * @throws \app\common\lib\exception\ApiException
     */
    public function commentReplyDataReset($uid, array $ids, array $commentReplyDatas, int $isOld = 2)
    {
        $userIds = [];
        foreach ($commentReplyDatas as $commentReplyDataItem)
        {
            $userIds[] = $commentReplyDataItem['uid1'];
            $userIds[] = $commentReplyDataItem['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        // 批量获取用户信息
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['avatar', 'nickname']);
        // 获取用户点赞信息
        $replyGoods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 2) : [];
        // 女神头像信息
        $goddessInfo = null;
        $resData = [];
        //获取内部官方用户
        $configModel = new ConfigManage();
        $userVipModel = new ZlUserVip();
        $goddessInfoModel = new GoddessBaseInfo();
        foreach ($ids as $id)
        {
            if ($isOld === 2 && $commentReplyDatas[$id]['is_goddess'] && is_null($goddessInfo))
            {
                $goddessInfo = $goddessInfoModel->getInfo(['nickname', 'avatar']);
            }
            if ($isOld === 2 && $commentReplyDatas[$id]['is_goddess'])
            {   // 女神回复
                $avatar = $goddessInfo['avatar'] ?? '';
                $nickname1 = $goddessInfo['nickname'] ?? '';
            } else
            {   // 用户回复
                $avatar = $userInfoList[$commentReplyDatas[$id]['uid1']]['avatar'] ?? '';
                $nickname1 = $userInfoList[$commentReplyDatas[$id]['uid1']]['nickname'] ?? '匿名用户';
            }
            if ($isOld === 1)
            {   // 旧版本数据
                $resData[] = [
                    'id' => (int)$id,
                    'avatar' => $avatar,
                    'nickname1' => $nickname1,
                    'nickname2' => $commentReplyDatas[$id]['pid'] ? (isset($userInfoList[$commentReplyDatas[$id]['uid2']]) ? $userInfoList[$commentReplyDatas[$id]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户') : null,
                    'aid' => $commentReplyDatas[$id]['aid'] ?? 0,
                    'pid' => $commentReplyDatas[$id]['pid'] ?? 0,
                    'title' => '',
                    'content1' => '',
                    'avatar1' => '',
                    'avatar2' => '',
                    'content2' => '',
                    'create_time' => (int)$commentReplyDatas[$id]['create_time'],
                    'content' => htmlspecialchars_decode($commentReplyDatas[$id]['content'] ?? ''),
                    'vip' => $userVipModel->getUserVipLevel($commentReplyDatas[$id]['uid1']),
                ];
            } else
            {
                $userType = $commentReplyDatas[$id]['is_goddess'] ? 2 : $configModel->innerUser((int)($commentReplyDatas[$id]['uid1'] ?? 0));
                // 获取用户当前装扮信息
                $adorn = (new AppUserAdornInfo())->getUserAdornInfo($commentReplyDatas[$id]['uid1'], $userType);
                // 新版本数据
                $resData[] = [
                    'id' => (int)$id,
                    'avatar' => $avatar,
                    'nickname1' => $nickname1,
                    'nickname2' => $commentReplyDatas[$id]['pid'] ? (isset($userInfoList[$commentReplyDatas[$id]['uid2']]) ? $userInfoList[$commentReplyDatas[$id]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户') : null,
                    'time' => $isOld === 1 ? (int)$commentReplyDatas[$id]['create_time'] : Util::timeToStr($commentReplyDatas[$id]['create_time']),
                    'content_type' => (int)($commentReplyDatas[$id]['content_type'] ?? 1),
                    'content' => htmlspecialchars_decode($commentReplyDatas[$id]['content'] ?? ''),
                    'good_num' => abs($commentReplyDatas[$id]['good_num']),
                    'is_good' => in_array($id, $replyGoods) ? 1 : 0,
                    'is_owner' => $uid == $commentReplyDatas[$id]['uid1'] ? 1 : 0,
                    'is_goddess' => (int)$commentReplyDatas[$id]['is_goddess'],
                    'duration' => (int)$commentReplyDatas[$id]['duration'],
                    'vip' => $userVipModel->getUserVipLevel($commentReplyDatas[$id]['uid1']),
                    'user_type' => $userType,//获取内部官方用户
                    'avatar_adorn' => $adorn['adorn_info']['reality_img'],
                    'badge' => array_column($adorn['badge_info'], 'reality_img'),
                ];
            }
        }
        return $resData;
    }

    /**
     * 分页数据重组
     * @param $uid
     * @param int $commentUid
     * @param int $questionUid
     * @param array $ids
     * @param array $commentReplyDatas
     * @return array
     * @throws ApiException
     */
    public function questionAnswerCommentReplyDataReset($uid, int $commentUid, int $questionUid, array $ids, array $commentReplyDatas)
    {
        $userIds = [];
        foreach ($commentReplyDatas as $commentReplyDataItem)
        {
            $userIds[] = $commentReplyDataItem['uid1'];
            $userIds[] = $commentReplyDataItem['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        // 批量获取用户信息
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['avatar', 'nickname']);
        // 获取用户点赞信息
        $replyGoods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 2) : [];
        $resData = [];
        //获取内部官方用户
        $userVipModel = new ZlUserVip();
        $configModel = new ConfigManage();
        foreach ($ids as $id)
        {
            $userTag = 0;
            $nickname2 = null;
            if ($questionUid === (int)$commentReplyDatas[$id]['uid1'])
            {
                $userTag = 1;
            } elseif ($commentUid === (int)$commentReplyDatas[$id]['uid1'])
            {
                $userTag = 2;
            }
            // 用户回复
            $avatar = $userInfoList[$commentReplyDatas[$id]['uid1']]['avatar'] ?? '';
            $nickname1 = $userInfoList[$commentReplyDatas[$id]['uid1']]['nickname'] ?? '匿名用户';

            if ($commentReplyDatas[$id]['pid'])
            {
                if ($this->isAnonymity && $questionUid === (int)$commentReplyDatas[$id]['uid2'])
                {
                    $nickname2 = '匿名';
                } else
                {
                    $nickname2 = isset($userInfoList[$commentReplyDatas[$id]['uid2']]) ? $userInfoList[$commentReplyDatas[$id]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户';
                }
            }

            // 新版本数据
            $resData[] = [
                'id' => (int)$id,
                'avatar1' => $userTag === 1 && $this->isAnonymity ? $this->anonymityAvatar : $avatar,
                'avatar_adorn1' => $userTag === 1 && $this->isAnonymity ? '' : Util::getUserAdorn($commentReplyDatas[$id]['uid1'])['avatar_adorn'],
                'nickname1' => $userTag === 1 && $this->isAnonymity ? $this->anonymityNickname : $nickname1,
                'nickname2' => $nickname2,
                'create_time' => Util::timeToStr($commentReplyDatas[$id]['create_time']),
                'content' => htmlspecialchars_decode($commentReplyDatas[$id]['content'] ?? ''),
                'good_num' => abs($commentReplyDatas[$id]['good_num']),
                'is_good' => in_array($id, $replyGoods, false) ? 1 : 0,
                'is_owner' => $uid == $commentReplyDatas[$id]['uid1'] ? 1 : 0,
                'vip' => $userVipModel->getUserVipLevel($commentReplyDatas[$id]['uid1']),
                'user_tag' => $userTag ?? 0,
                'user_type' => $configModel->innerUser((int)($commentReplyDatas[$id]['uid1'] ?? 0)), //获取内部官方用户
            ];
        }

        return $resData;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type null
     * @param $sortType null
     * @return array
     * @throws Exception
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        //uid1=>二级回复,ud2=>一级回复,uid3=>评论
        try
        {
            $data = $this->alias('cr')
                ->join('wechatadmin.system_article_comment ac', 'cr.comment_id=ac.id', 'LEFT')
                ->join('wechatadmin.system_comment_reply cr2', 'cr.pid=cr2.id', 'LEFT')
                ->whereIn('cr.id', $ids)
                ->column('cr.id,cr.create_time,cr.content,cr.duration,cr.pid,cr.comment_id,cr.good_num,cr.uid uid1,cr2.uid uid2,cr2.content content2,cr.is_goddess,cr.content_type,cr.type,cr.aid,ac.uid uid3,ac.content content3', 'cr.id');

            $res = [];
            foreach ($data as $id => $item)
            {
                if (!$item['pid'])
                {
                    $item['uid2'] = $item['uid3'];
                    $item['content2'] = $item['content3'];
                }
                unset($item['uid3'], $item['content3']);
                $res[$id] = $item;
            }
            $data = $res;
        }
        catch (Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取评论盖楼数据 最近的回复信息
     * @param int $commentId
     * @param int $limit 盖楼层数
     * @return array
     * @throws Exception
     */
    public function getLimtData(int $commentId, int $limit = 3)
    {
        $replyIds = $this->getCommentReplyAllIds($commentId);

        $replyIds = array_slice($replyIds, 0, $limit);

        // 通过ids 批量获取话题详情
        $commentReplyDatas = $this->batchGetInfoByIds($replyIds, ['content', 'uid1', 'uid2']);

        $userIds = [];
        foreach ($commentReplyDatas as $replyId => $replyData)
        {
            $userIds[] = $replyData['uid1'];
            $userIds[] = $replyData['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['nickname']);

        $resData = [];
        //获取内部官方用户
        $configModel = new ConfigManage();
        foreach ($replyIds as $replyId)
        {
            $resData[] = [
                'id' => $replyId,
                'user_type' => $configModel->innerUser((int)($commentReplyDatas[$replyId]['uid1'] ?? 0)), //获取内部官方用户
                'nickname1' => isset($userInfoList[$commentReplyDatas[$replyId]['uid1']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid1']]['nickname'] : '匿名用户',
                'nickname2' => $commentReplyDatas[$replyId]['uid2'] ? (isset($userInfoList[$commentReplyDatas[$replyId]['uid2']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户') : null,
                'content' => htmlspecialchars_decode($commentReplyDatas[$replyId]['content']),
            ];
        }

        return $resData;
    }

    /**
     * 获取 问答 评论盖楼数据 最近的回复信息
     * @param int $questionUid 提问用户uid
     * @param int $commentUid 讨论uid
     * @param int $uid 当前用户uid
     * @param int $commentId
     * @param array $userVipList 用户VIP列表
     * @param int $limit
     * @return array
     * @throws ApiException
     */
    public function getQuestionAnswerLimtData(int $questionUid, int $commentUid, int $uid, int $commentId, array &$userVipList, int $limit = 2)
    {
        $replyIds = $this->getCommentReplyAllIds($commentId);

        $replyIds = array_slice($replyIds, 0, $limit);

        // 通过ids 批量获取话题详情
        $commentReplyDatas = $this->batchGetInfoByIds($replyIds, ['content', 'uid1', 'uid2', 'uid3', 'pid', 'create_time', 'good_num']);

        $userIds = [];
        foreach ($commentReplyDatas as $replyId => $replyData)
        {
            $userIds[] = $replyData['uid1'];
            $userIds[] = $replyData['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['nickname', 'avatar']);
        // 获取用户点赞信息
        $replyGoods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 2) : [];
        $resData = [];
        //获取内部官方用户
        $configModel = new ConfigManage();
        foreach ($replyIds as $replyId)
        {
            $commentReplyDatas[$replyId]['uid1'] = (int)($commentReplyDatas[$replyId]['uid1'] ?? 0);
            if ($commentReplyDatas[$replyId]['pid'])
            {
                if ($this->isAnonymity && $questionUid === (int)$commentReplyDatas[$replyId]['uid2'])
                {
                    $nickname2 = '匿名';
                } else
                {
                    $nickname2 = $commentReplyDatas[$replyId]['uid2'] ? (isset($userInfoList[$commentReplyDatas[$replyId]['uid2']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户') : null;
                }
            } else
            {
                $nickname2 = null;
            }

            $userTag = 0;
            if ($questionUid === $commentReplyDatas[$replyId]['uid1'])
            {
                $userTag = 1; // 用户标签 0=>没有  1=>提问者 2=>楼主
            } elseif ($commentUid === $commentReplyDatas[$replyId]['uid1'])
            {
                $userTag = 2; // 用户标签 0=>没有  1=>提问者 2=>楼主
            }

            if (!isset($userVipList[$commentReplyDatas[$replyId]['uid1']]))
            {
                $userVipList[$commentReplyDatas[$replyId]['uid1']] = (new ZlUserVip())->getUserVipLevel($commentReplyDatas[$replyId]['uid1']);
            }

            $vip = $userVipList[$commentReplyDatas[$replyId]['uid1']];

            $resData[] = [
                'id' => (int)$replyId,
                'nickname1' => ($userTag === 1 && $this->isAnonymity) ? $this->anonymityNickname : (isset($userInfoList[$commentReplyDatas[$replyId]['uid1']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid1']]['nickname'] : '匿名用户'),
                'avatar1' => ($userTag === 1 && $this->isAnonymity) ? $this->anonymityAvatar : (isset($userInfoList[$commentReplyDatas[$replyId]['uid1']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid1']]['avatar'] : ''),
                'avatar_adorn1' => ($userTag === 1 && $this->isAnonymity) ? '' : Util::getUserAdorn($commentReplyDatas[$replyId]['uid1'])['avatar_adorn'],
                'nickname2' => $nickname2,
                'content' => htmlspecialchars_decode($commentReplyDatas[$replyId]['content']),
                'good_num' => (int)$commentReplyDatas[$replyId]['good_num'],
                'is_good' => in_array($replyId, $replyGoods, false) ? 1 : 0,
                'is_owner' => $uid === (int)$commentReplyDatas[$replyId]['uid1'] ? 1 : 0,
                'create_time' => Util::timeToStr($commentReplyDatas[$replyId]['create_time']),
                'user_tag' => $userTag ?? 0, // 用户标签 0=>没有  1=>提问者 2=>楼主
                'vip' => $vip,
                'user_type' => $configModel->innerUser($commentReplyDatas[$replyId]['uid1']), //获取内部官方用户
            ];
        }

        return $resData;
    }

    /**
     * 获取 星座讨论 评论盖楼数据 最近的回复信息
     * @param int $questionUid 提问用户uid
     * @param int $commentUid 讨论uid
     * @param int $uid 当前用户uid
     * @param int $commentId
     * @param array $userVipList 用户VIP列表
     * @param int $limit
     * @return array
     * @throws ApiException
     */
    public function getAstrArticleLimtData(int $questionUid, int $commentUid, int $uid, int $commentId, array &$userVipList, int $limit = 2)
    {
        $replyIds = $this->getCommentReplyAllIds($commentId);

        $replyIds = array_slice($replyIds, 0, $limit);

        // 通过ids 批量获取话题详情
        $commentReplyDatas = $this->batchGetInfoByIds($replyIds, ['content', 'uid1', 'uid2', 'uid3', 'pid', 'create_time', 'good_num']);

        $userIds = [];
        foreach ($commentReplyDatas as $replyId => $replyData)
        {
            $userIds[] = $replyData['uid1'];
            $userIds[] = $replyData['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['nickname', 'avatar']);
        // 获取用户点赞信息
        $replyGoods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 2) : [];
        $resData = [];
        //获取内部官方用户
        $configModel = new ConfigManage();
        foreach ($replyIds as $replyId)
        {
            $commentReplyDatas[$replyId]['uid1'] = (int)($commentReplyDatas[$replyId]['uid1'] ?? 0);
            if ($commentReplyDatas[$replyId]['pid'])
            {
                if ($this->isAnonymity && $questionUid === (int)$commentReplyDatas[$replyId]['uid2'])
                {
                    $nickname2 = '匿名';
                } else
                {
                    $nickname2 = $commentReplyDatas[$replyId]['uid2'] ? (isset($userInfoList[$commentReplyDatas[$replyId]['uid2']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户') : null;
                }
            } else
            {
                $nickname2 = null;
            }

            $userTag = 0;
            if ($questionUid === $commentReplyDatas[$replyId]['uid1'])
            {
                $userTag = 1; // 用户标签 0=>没有  1=>提问者 2=>楼主
            } elseif ($commentUid === $commentReplyDatas[$replyId]['uid1'])
            {
                $userTag = 2; // 用户标签 0=>没有  1=>提问者 2=>楼主
            }

            if (!isset($userVipList[$commentReplyDatas[$replyId]['uid1']]))
            {
                $userVipList[$commentReplyDatas[$replyId]['uid1']] = (new ZlUserVip())->getUserVipLevel($commentReplyDatas[$replyId]['uid1']);
            }

            $vip = $userVipList[$commentReplyDatas[$replyId]['uid1']];

            $resData[] = [
                'id' => (int)$replyId,
                'nickname1' => ($userTag === 1 && $this->isAnonymity) ? $this->anonymityNickname : (isset($userInfoList[$commentReplyDatas[$replyId]['uid1']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid1']]['nickname'] : '匿名用户'),
                'avatar1' => ($userTag === 1 && $this->isAnonymity) ? $this->anonymityAvatar : (isset($userInfoList[$commentReplyDatas[$replyId]['uid1']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid1']]['avatar'] : ''),
                'avatar_adorn1' => ($userTag === 1 && $this->isAnonymity) ? '' : Util::getUserAdorn($commentReplyDatas[$replyId]['uid1'])['avatar_adorn'],
                'nickname2' => $nickname2,
                'content' => htmlspecialchars_decode($commentReplyDatas[$replyId]['content']),
                'good_num' => (int)$commentReplyDatas[$replyId]['good_num'],
                'is_good' => in_array($replyId, $replyGoods, false) ? 1 : 0,
                'is_owner' => $uid === (int)$commentReplyDatas[$replyId]['uid1'] ? 1 : 0,
                'create_time' => Util::timeToStr($commentReplyDatas[$replyId]['create_time']),
                'user_tag' => $userTag ?? 0, // 用户标签 0=>没有  1=>提问者 2=>楼主
                'vip' => $vip,
                'user_type' => $configModel->innerUser($commentReplyDatas[$replyId]['uid1']), //获取内部官方用户
            ];
        }

        return $resData;
    }

    /**
     * 获取评论盖楼数据 最近的回复信息 旧版本信息
     * @param int $commentId
     * @param int $limit 盖楼层数
     * @return array
     * @throws Exception
     */
    public function getLimtDataOld(int $commentId, int $limit = 3)
    {
        $replyIds = $this->getCommentReplyAllIds($commentId);

        $replyIds = array_slice($replyIds, 0, $limit);

        // 通过ids 批量获取话题详情
        $commentReplyDatas = $this->batchGetInfoByIds($replyIds, ['id', 'create_time', 'content', 'aid', 'pid', 'uid1', 'uid2']);

        $userIds = [];
        foreach ($commentReplyDatas as $replyId => $replyData)
        {
            $userIds[] = $replyData['uid1'];
            $userIds[] = $replyData['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['nickname']);

        $resData = [];

        foreach ($replyIds as $replyId)
        {
            $resData[] = [
                'id' => $replyId,
                'create_time' => (int)$commentReplyDatas[$replyId]['create_time'],
                'content' => htmlspecialchars_decode($commentReplyDatas[$replyId]['content']),
                'aid' => (int)$commentReplyDatas[$replyId]['aid'],
                'pid' => (int)$commentReplyDatas[$replyId]['pid'],
                'title' => '',
                'avatar' => null,
                'avatar1' => null,
                'avatar2' => null,
                'content1' => '',
                'content2' => '',
                'vip' => 0,
                'nickname1' => isset($userInfoList[$commentReplyDatas[$replyId]['uid1']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid1']]['nickname'] : '匿名用户',
                'nickname2' => $commentReplyDatas[$replyId]['uid2'] ? (isset($userInfoList[$commentReplyDatas[$replyId]['uid2']]) ? $userInfoList[$commentReplyDatas[$replyId]['uid2']]['nickname'] ?? '匿名用户' : '匿名用户') : null,
            ];
        }

        return $resData;
    }
}
